<?php

/**
 *    客户管理控制器
 *
 *    @author    yanghj
 *    @date    2015.01.22
 */
class customerApp extends BackendApp
{
    /**
     *   查看列表
     */
    function index()
    {
        $search_options = array(
            'customer_name'   => '客户姓名',
            'user_name'   => '会员名称',
            'phone_mob'   => '手机号码',
            'im_qq'   => 'QQ号码',
        );
        $customer = $this->_get_customer();
        $cfg_customer = $this->_get_cfg_msg();
        $this->assign('search_options', $search_options);
        $this->assign('cfg_customer' , $cfg_customer);
        $this->assign('customers', $customer['data']);
        $this->assign('page_info', $customer['page']);
        $this->assign('filtered', $customer['filtered']);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('customer.index.html');
    }

    /**
     *   查看客户回访记录
     */
    function view_record()
    {
        $model_customer =& m('customer');
        $customer_id = isset($_GET['id']) ? trim($_GET['id']) : 0;
        $customer_data =  $model_customer->get_info($customer_id);
        if(!$customer_data)
        {
            $this->show_warning('没有相关客户的数据');
            return;
        }
        $cfg_customer = $this->_get_cfg_msg();
        $customer_data['customer_ugrade'] = $cfg_customer['customer_ugrade'][$customer_data['customer_ugrade']];
        $customer_record = $this->_get_customer_record($customer_id);
        $this->assign('customers_record', $customer_record['data']);
        $this->assign('customer_data', $customer_data);
        $this->assign('page_info', $customer_record['page']);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('customer_record.index.html');
    }

    /**
     *   添加数据
     */
    function add()
    {

        if (!IS_POST)
        {
            $cfg_customer = $this->_get_cfg_msg();
            $this->assign('cfg_customer' , $cfg_customer);
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            $this->display('customer.form.html');
        }
        else
        {

            $customer_name = html_script(trim($_POST['customer_name']));
            $source = isset($_POST['source']) ? intval($_POST['source']) : intval($_POST['source_1']);
            $user_name = isset($_POST['user_name']) ? html_script(trim($_POST['user_name'])) : html_script(trim($_POST['user_name_1']));
            $phone_mob = isset($_POST['phone_mob']) ? html_script(trim($_POST['phone_mob'])) : html_script(trim($_POST['phone_mob_1']));
            $im_qq = isset($_POST['im_qq']) ? html_script(trim($_POST['im_qq'])) : html_script(trim($_POST['im_qq_1']));
            $ajax_rs = array('state'=>false, 'msg'=>'');
            /*if(empty($customer_name))
            {
                $this->show_warning("客户姓名不能为空");
                return;
            }*/
            if($source == 1 || $source == 4)
            {
                if(empty($user_name))
                {
                    $ajax_rs['msg'] = '会员名称不能为空';
                    echo ecm_json_encode($ajax_rs);
                    return;
                }
                $rs = $this->_is_customer('user_name', $user_name, 0, $source);
                if($rs)
                {
                    $ajax_rs['msg'] = '该会员名称已经存在,请重新填写';
                    echo ecm_json_encode($ajax_rs);
                    return;

                }
            }
            else if($source == 5)
            {

                if(empty($phone_mob) && empty($im_qq))
                {
                    $ajax_rs['msg'] = '手机和QQ号码不能同时为空';
                    echo ecm_json_encode($ajax_rs);
                    return;
                }

                if(!empty($phone_mob))
                {
                    $rs = $this->_is_customer('phone_mob', $phone_mob, 0, $source);
                    if($rs)
                    {
                        $ajax_rs['msg'] = '该手机号码已经存在,请重新填写';
                        echo ecm_json_encode($ajax_rs);
                        return;
                    }
                }

                if(!empty($im_qq))
                {
                    $rs = $this->_is_customer('im_qq', $im_qq, 0, $source);
                    if($rs)
                    {
                        $ajax_rs['msg'] = '该QQ号码已经存在,请重新填写';
                        echo ecm_json_encode($ajax_rs);
                        return;
                    }
                }

            }
            else
            {
                if(empty($phone_mob))
                {
                    $ajax_rs['msg'] = '手机不能为空';
                    echo ecm_json_encode($ajax_rs);
                    return;
                }
                $rs = $this->_is_customer('phone_mob', $phone_mob, 0, $source);
                if($rs)
                {
                    $ajax_rs['msg'] = '该手机号码已经存在,请重新填写';
                    echo ecm_json_encode($ajax_rs);
                    return;
                }

            }

            $model_customer =& m('customer');

            $data['customer_name']    =   $customer_name;
            $data['user_name']        =   $user_name;
            $data['company']          =   html_script(trim($_POST['company']));
            $data['email']            =   html_script(trim($_POST['email']));
            $data['phone_mob']        =   $phone_mob;
            $data['im_qq']            =   $im_qq;
            $data['city']             =   html_script(trim($_POST['city']));
            $data['address']          =   html_script(trim($_POST['address']));
            $data['customer_ugrade']  =   intval($_POST['customer_ugrade']);
            $data['source']           =   $source;
            $data['add_time']         =   gmtime();
            $data['operator']         =   $this->visitor->get('real_name');
            $data['admin_name']       =   $this->visitor->get('user_name');

            if (!$customer_id = $model_customer->add($data))
            {
                $ajax_rs['msg'] = '数据入库错误';
                echo ecm_json_encode($ajax_rs);
                return;
            }
            $this->admin_log('添加客户关系信息,ID:'.$customer_id.'客户名称:'.$data['customer_name']);

            $ajax_rs['state'] = true;
            $ajax_rs['msg'] = '添加成功';
            echo ecm_json_encode($ajax_rs);
            return;
        }
    }

    /**
     *   添加回访记录数据
     */
    function add_record()
    {
        $customer_id = isset($_GET['id']) ? trim($_GET['id']) : 0;
        $model_customer =& m('customer');
        $customer = $model_customer->get_info($customer_id);
        if(!$customer)
        {
            $this->show_warning('没有相关客户的数据');
            return;
        }
        if (!IS_POST)
        {
            $cfg_customer = $this->_get_cfg_msg();
            $this->assign('cfg_customer' , $cfg_customer);
            $this->assign('customer_id' , $customer_id);
            $this->assign('customer' , $customer);
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            $this->display('customer_record.form.html');
        }
        else
        {

            $data['customer_id']      =   $customer_id;
            $data['add_time']         =   gmtime();
            $data['return_way']       =   intval($_POST['return_way']);
            $data['return_time']      =   strtotime(trim($_POST['return_time']));
            $data['return_content']   =   html_script(trim($_POST['return_content']));
            $data['return_reply']     =   html_script(trim($_POST['return_reply']));
            $data['reason']           =   intval($_POST['reason']);
            $data['operator']         =   $this->visitor->get('real_name');
            $data['admin_name']       =   $this->visitor->get('user_name');

            if(empty($data['return_time']) || empty($data['return_content']) || empty($data['return_reply']))
            {
                $this->show_warning("数据填写不正确!");
                return;
            }
            $customerrecord_customer =& m('customerrecord');
            if (!$record_id = $customerrecord_customer->add($data))
            {
                $this->show_warning($customerrecord_customer->get_error());
                return;
            }
            $this->admin_log('添加客户回访记录,ID:'.$record_id);

            $this->show_message('添加成功',
                'back_list',    'index.php?app=customer'
            );
        }
    }

    /**
     *    修改数据
     */
    function edit()
    {
        $id = isset($_GET['id']) ? trim($_GET['id']) : 0;
        $model_customer =& m('customer');
        if (!$id)
        {
            $this->show_warning('没有相关的数据');
            return;
        }

        if (!IS_POST)
        {

            $customer = $model_customer->get_info($id);
            if(!$customer)
            {
                $this->show_warning('没有相关的数据');
                return;
            }
            $cfg_customer = $this->_get_cfg_msg();
            $this->assign('cfg_customer' , $cfg_customer);
            $this->assign('customer' , $customer);
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            $this->display('customer.form.html');
        }
        else
        {

            $customer_name = html_script(trim($_POST['customer_name']));
            $source = isset($_POST['source']) ? intval($_POST['source']) : intval($_POST['source_1']);
            $user_name = isset($_POST['user_name']) ? html_script(trim($_POST['user_name'])) : html_script(trim($_POST['user_name_1']));
            $phone_mob = isset($_POST['phone_mob']) ? html_script(trim($_POST['phone_mob'])) : html_script(trim($_POST['phone_mob_1']));
            $im_qq = isset($_POST['im_qq']) ? html_script(trim($_POST['im_qq'])) : html_script(trim($_POST['im_qq_1']));
            $ajax_rs = array('state'=>false, 'msg'=>'');
            /*if(empty($customer_name))
            {
                $this->show_warning("客户姓名不能为空");
                return;
            }*/

            if($source == 1 || $source == 4)
            {
                if(empty($user_name))
                {
                    $ajax_rs['msg'] = '会员名称不能为空';
                    echo ecm_json_encode($ajax_rs);
                    return;
                }
                $rs = $this->_is_customer('user_name', $user_name, $id, $source);
                if($rs)
                {
                    $ajax_rs['msg'] = '该会员名称已经存在,请重新填写';
                    echo ecm_json_encode($ajax_rs);
                    return;

                }
            }
            else if($source == 5)
            {

                if(empty($phone_mob) && empty($im_qq))
                {
                    $ajax_rs['msg'] = '手机和QQ号码不能同时为空';
                    echo ecm_json_encode($ajax_rs);
                    return;
                }

                if(!empty($phone_mob))
                {
                    $rs = $this->_is_customer('phone_mob', $phone_mob, $id, $source);
                    if($rs)
                    {
                        $ajax_rs['msg'] = '该手机号码已经存在,请重新填写';
                        echo ecm_json_encode($ajax_rs);
                        return;
                    }
                }

                if(!empty($im_qq))
                {
                    $rs = $this->_is_customer('im_qq', $im_qq, $id, $source);
                    if($rs)
                    {
                        $ajax_rs['msg'] = '该QQ号码已经存在,请重新填写';
                        echo ecm_json_encode($ajax_rs);
                        return;
                    }
                }

            }
            else
            {
                if(empty($phone_mob))
                {
                    $ajax_rs['msg'] = '手机不能为空';
                    echo ecm_json_encode($ajax_rs);
                    return;
                }
                $rs = $this->_is_customer('phone_mob', $phone_mob, $id, $source);
                if($rs)
                {
                    $ajax_rs['msg'] = '该手机号码已经存在,请重新填写';
                    echo ecm_json_encode($ajax_rs);
                    return;
                }

            }

            $model_customer =& m('customer');

            $data['customer_name']    =   $customer_name;
            $data['user_name']        =   $user_name;
            $data['company']          =   html_script(trim($_POST['company']));
            $data['email']            =   html_script(trim($_POST['email']));
            $data['phone_mob']        =   $phone_mob;
            $data['im_qq']            =   html_script(trim($_POST['im_qq']));
            $data['city']             =   html_script(trim($_POST['city']));
            $data['address']          =   html_script(trim($_POST['address']));
            $data['customer_ugrade']  =   intval($_POST['customer_ugrade']);
            $data['source']           =   $source;
            $data['operator']         =   $this->visitor->get('real_name');
            $data['admin_name']       =   $this->visitor->get('user_name');

            $model_customer->edit($id, $data);
            if ($model_customer->has_error())
            {
                $ajax_rs['msg'] = '数据入库错误';
                echo ecm_json_encode($ajax_rs);
                return;
            }

            $this->admin_log('修改客户关系信息,ID:'.$id.'客户名称:'.$data['customer_name']);

            $ajax_rs['state'] = true;
            $ajax_rs['msg'] = '修改成功';
            echo ecm_json_encode($ajax_rs);
            return;
        }
    }

    /**
     *    删除数据
     */
    function drop()
    {
        $customer_ids = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$customer_ids)
        {
            $this->show_warning('没有相关的数据');

            return;
        }
        $model_customer =& m('customer');
        $ids=explode(',', $customer_ids);

        $this->admin_log('删除客户关系信息:ID:'.$customer_ids);

        if (!$model_customer->drop($ids))    //删除
        {
            $this->show_warning($model_customer->get_error());

            return;
        }

        $this->show_message('删除成功!');
    }

    /**
     *    导出数据
     */
    function export()
    {

        $export_type = isset($_GET['export_type'])? intval($_GET['export_type']) : 1;
        //导出数据

        if($export_type == 1)
        {
            $data = $this->_get_customer(true);
            $export_data = $data['data'];
            if($export_data)
            {
                if(count($export_data) > 10000){
                    echo "<script>alert('数据量不能大于10000，请筛选查询分批导出');history.back();</script>";
                    exit;
                }
                else
                {
                    $heads = $this->_get_excel_heads();
                    //require(ROOT_PATH."/includes/PHPExcel/export_excel.php");
                    // createExcel('CRM客户关系信息', $heads, $export_data);
                    export_excel('CRM客户关系信息', $heads, $export_data);
                    exit;
                }

            }
            else
            {
                echo "<script>alert('没有相关的数据');history.back();</script>";
                exit;
            }
        }
        else if($export_type == 2)
        {
            $model_customer =& m('customer');
            $customer_id = isset($_GET['id']) ? trim($_GET['id']) : 0;
            $customer_data =  $model_customer->get_info($customer_id);
            if(!$customer_data)
            {
                $this->show_warning('没有相关客户的数据');
                return;
            }
            $cfg_customer = $this->_get_cfg_msg();
            $customer_data['customer_ugrade'] = $cfg_customer['customer_ugrade'][$customer_data['customer_ugrade']];
            $customer_data['source_name'] = $cfg_customer['source'][$customer_data['source']];
            $data = $this->_get_customer_record($customer_id,true);
            $export_data = $data['data'];
            if($export_data)
            {
                foreach($export_data as $key=>$val)
                {
                    $export_data[$key]['customer_ugrade'] = $customer_data['customer_ugrade'];
                }
            }
            else
            {
                $this->show_warning('没有相关客户回访的数据');
                return;
            }

            if($customer_data['source'] == 5)
            {
                $heads = $this->_get_excel_heads_2();
            }
            else
            {
                $heads = $this->_get_excel_heads_1();
            }

            $title = '会员名称: '.$customer_data['user_name'].'　手机: '.$customer_data['phone_mob'].'　QQ: '.$customer_data['im_qq'].'　 资料来源: '.$customer_data['source_name'];
            require(ROOT_PATH."/includes/PHPExcel/export_excel.php");
            createExcel('CRM客户关系信息', $heads, $export_data, 1, $title);
            exit;
        }
        else if($export_type == 3)
        {
            if(empty($_GET['return_time_from']) || empty($_GET['return_time_to']))
            {
                $this->show_warning('请选择回访时间');
                return;
            }
            $conditions = $this->_get_query_conditions(array(array(
                    'field' => 'return_time',
                    'name'  => 'return_time_from',
                    'equal' => '>=',
                    'handler'=> 'gmstr2time',
                ),array(
                    'field' => 'return_time',
                    'name'  => 'return_time_to',
                    'equal' => '<',
                    'handler'   => 'gmstr2time_end',
                )
            ));
            $model_customer_record =& m('customerrecord');
            $export_data = $model_customer_record->find(array(
                'conditions' => '1=1 '.$conditions,
                'fields' => 'this.return_way,this.return_time,this.return_content,this.return_reply,this.reason,this.operator,customer.customer_name,customer.user_name,customer.phone_mob,customer.im_qq,customer.customer_ugrade',
                'join' => 'belongs_to_customer',
                'order' => "customer.customer_id asc,customer_record.return_time asc",
            ));
            if($export_data)
            {
                if(count($export_data) > 10000){
                    echo "<script>alert('数据量不能大于10000，请筛选查询分批导出');history.back();</script>";
                    exit;
                }
                else
                {
                    $cfg_customer = $this->_get_cfg_msg();//配置文件
                    foreach($export_data as $key => $val)
                    {
                        $export_data[$key]['return_time'] = date('Y-m-d',$val['return_time']);
                        $export_data[$key]['customer_ugrade'] = $cfg_customer['customer_ugrade'][$val['customer_ugrade']];
                        $export_data[$key]['return_way'] = $cfg_customer['return_way'][$val['return_way']];
                        $export_data[$key]['reason'] = $cfg_customer['reason'][$val['reason']];
                    }
                    $heads = $this->_get_excel_heads_3();
                    require(ROOT_PATH."/includes/PHPExcel/export_excel.php");
                    createExcel('CRM客户关系信息', $heads, $export_data);
                    //export_excel('CRM客户关系信息', $heads, $export_data);
                    exit;
                }

            }
            else
            {
                echo "<script>alert('没有相关的数据');history.back();</script>";
                exit;
            }

        }

    }

    /**
     *    判断客户资料否是存在
     *
     */
    function check_customer()
    {
        $user_name = empty($_GET['user_name']) ? null : trim($_GET['user_name']);
        $phone_mob = empty($_GET['phone_mob']) ? null : trim($_GET['phone_mob']);
        $im_qq = empty($_GET['im_qq']) ? null : trim($_GET['im_qq']);
        $customer_id = empty($_GET['customer_id']) ? 0 : trim($_GET['customer_id']);
        $source = empty($_GET['source']) ? 0 : trim($_GET['source']);
        if ($user_name)
        {
            $rs = $this->_is_customer('user_name', $user_name, $customer_id, $source);
            if($rs)
            {
                echo ecm_json_encode(false);
                return;
            }
            else
            {
                echo ecm_json_encode(true);
                return;
            }
        }

        if ($phone_mob)
        {
            $rs = $this->_is_customer('phone_mob', $phone_mob, $customer_id, $source);
            if($rs)
            {
                echo ecm_json_encode(false);
                return;
            }
            else
            {
                echo ecm_json_encode(true);
                return;
            }
        }

        if ($im_qq)
        {
            $rs = $this->_is_customer('im_qq', $im_qq, $customer_id, $source);
            if($rs)
            {
                echo ecm_json_encode(false);
                return;
            }
            else
            {
                echo ecm_json_encode(true);
                return;
            }
        }

    }

    /**
     *    判断客户资料否是存在
     */
    function _is_customer($fields, $val , $customer_id = 0 ,$source = 0)
    {
        if(!$fields || !$val)
        {
            return false;
        }
        $conditions = $fields . "='" .$val."'";
        if($customer_id > 0)
        {
            $conditions .= " AND customer_id != {$customer_id}";
        }
        if($source > 0)
        {
            $conditions .= " AND source = {$source}";
        }
        $model_customer =& m('customer');
        $customer =  $model_customer->get(array(
            'conditions' => $conditions,
            'fields' => $fields,
        ));

        if($customer)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    /**
     *    导入数据
     */
    public function input_excel_customer()
    {

        $cache_server =& cache_server();
        $cache_key = 'input_excel_customer';
        $data = $cache_server->get($cache_key);
        $model_customer =& m('customer');
        //$data = false;
        if ($data === false)
        {
            set_time_limit(0);
            $file_excel = ROOT_PATH . '/WIFI.xls';

            if (file_exists($file_excel))
            {
                require_once ROOT_PATH . '/includes/PHPExcel/PHPExcel.php';
                $excel = PHPExcel_IOFactory::load($file_excel);
                $excel_data = $excel->getSheet(0)->toArray();
                foreach ($excel_data as $key => $item)
                {
                    $data[$key]['phone_mob'] = trim($item[0]) ;
                    $data[$key]['add_time'] = strtotime($item[1]);
                    $data[$key]['customer_ugrade'] = 4;
                    $data[$key]['source'] = 2;
                    $data[$key]['operator'] = '系统录入';
                    $data[$key]['admin_name'] = 'admin';
                }

                $cache_server->set($cache_key, $data, 3600);
            }

        }

       //var_dump($data);

        //$model_customer->add($data);
        //echo 'aa';
        exit;
    }

    /**
     *    导入数据
     */
    public function input_excel()
    {

        $cache_server =& cache_server();
        $cache_key = 'customer_input_excel';
        $data = $cache_server->get($cache_key);
        $model_customer =& m('customer');
        $model_customer_record =& m('customerrecord');
        //$data = false;
        if ($data === false)
        {
            set_time_limit(0);
            $file_excel = ROOT_PATH . '/customer.xls';

            if (file_exists($file_excel))
            {
                require_once ROOT_PATH . '/includes/PHPExcel/PHPExcel.php';
                $excel = PHPExcel_IOFactory::load($file_excel);
                $excel_data = $excel->getSheet(0)->toArray();
                foreach ($excel_data as $key => $item)
                {
                    $data[$key]['customer_id'] = intval($item[0]) ;
                    $data[$key]['return_time'] = strtotime($item[1]);
                    $data[$key]['return_way'] = $item[2];
                    $data[$key]['return_content'] = trim($item[3]);
                    $data[$key]['return_reply'] = trim($item[4]);
                    $data[$key]['operator'] = trim($item[5]);
                    $data[$key]['add_time'] = gmtime();
                    $data[$key]['reason'] = intval($item[6]);
                    if($item[7])
                    {
                        $display_order[intval($item[0])] = trim($item[7]);
                    }

                }

            $cache_server->set($cache_key, $data, 3600);
           // $cache_server->set($cache_key, $display_order, 3600);
            }

        }

        /*$ids = implode(',', array_keys($data));
        $sql = "UPDATE wl_customer SET customer_name = CASE customer_id ";
        foreach ($data as $id => $ordinal) {
            $sql .= sprintf("WHEN %d THEN '%s' ", $id, $ordinal);
        }
        $sql .= "END WHERE customer_id IN ($ids)";
        echo $sql;*/
        //var_dump($data);

       // $model_customer_record->add($data);
        //echo 'aa';
        exit;
    }

    /**
     *    获取客户信息列表
     */
    function _get_customer($is_excel = false)
    {

        $arr = array();
        $data = array();
        $page = $this->_get_page(10);
        $model_customer =& m('customer');
        $cfg_customer = $this->_get_cfg_msg();//配置文件
        $search_options = array(
            'customer_name'   => '客户姓名',
            'user_name'   => '会员名称',
            'phone_mob'   => '手机号码',
            'im_qq'   => 'QQ号码',
        );
        /* 默认搜索的字段是店铺名 */
        $field = 'customer_name';
        array_key_exists($_GET['field'], $search_options) && $field = $_GET['field'];

        $conditions = $this->_get_query_conditions(array(array(
                'field' => $field,
                'equal' => 'LIKE',
                'name'  => 'search_name',
                'handler' => 'html_script',
            ),array(
                'field' => 'c.add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'c.add_time',
                'name'  => 'add_time_to',
                'equal' => '<',
                'handler'   => 'gmstr2time_end',
            ),
            array(
                'field' => 'source',
                'equal' => '=',
                'type'  => 'numeric',
            ),
            array(
                'field' => 'return_way',
                'name' => 'return_way',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
                'field' => 'return_time',
                'name'  => 'return_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'return_time',
                'name'  => 'return_time_to',
                'equal' => '<',
                'handler'   => 'gmstr2time_end',
            )
        ));

        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
                $sort  = 'customer_id';
                $order = 'desc';
            }
        }
        else
        {
            $sort  = 'customer_id';
            $order = 'desc';
        }


        $limit = $is_excel ? '' : "LIMIT {$page['limit']}";
        $is_conditions = $conditions ? 1 : 0;


        $sql = "SELECT * FROM ".DB_PREFIX."customer c left join (SELECT customer_id as customer_ids,return_way,return_time,reason,operator as re_operator FROM ".DB_PREFIX."customer_record  order by return_time desc, record_id desc ) r on c.customer_id = r.customer_ids WHERE 1=1 {$conditions} group by c.customer_id ORDER BY {$sort} {$order} {$limit}";

        $customer = $model_customer->getAll($sql);
        if($customer)
        {
            foreach($customer as $key => $val)
            {
                $customer[$key]['customer_ugrade'] = $cfg_customer['customer_ugrade'][$val['customer_ugrade']];
                $customer[$key]['reason'] = $cfg_customer['reason'][$val['reason']];
                $customer[$key]['source'] = $cfg_customer['source'][$val['source']];
                $customer[$key]['return_way'] = !empty($val['return_time']) ? $cfg_customer['return_way'][$val['return_way']] : '';
                $customer[$key]['return_time'] = !empty($val['return_time']) ? date('Y-m-d',$val['return_time']) : '';
                $customer[$key]['reg_time'] = !empty($val['reg_time']) ? date('Y-m-d',$val['reg_time']) : '';
                $customer[$key]['add_time'] = !empty($val['add_time']) ? date('Y-m-d',$val['add_time']) : '';

            }
            $item_count = $model_customer->getOne("SELECT COUNT(DISTINCT c.customer_id) FROM ".DB_PREFIX."customer c left join ".DB_PREFIX."customer_record r on c.customer_id = r.customer_id WHERE 1=1 {$conditions} ");
            $page['item_count'] = !empty($item_count) ? $item_count : 0;
            $this->_format_page($page);
        }

        $arr['page'] = $page;
        $arr['data'] = $customer;
        $arr['filtered'] = $is_conditions;

        return $arr ;
    }

    /**
     *    获取客户访问记录列表
     */
    function _get_customer_record($customer_id, $is_excel = false)
    {

        $arr = array();
        $data = array();
        $page = $this->_get_page(10);
        $model_customer_record =& m('customerrecord');
        $cfg_customer = $this->_get_cfg_msg();//配置文件

        $conditions = " and customer_id = {$customer_id}";

        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
                $sort  = 'add_time';
                $order = 'desc';
            }
        }
        else
        {
            $sort  = 'add_time';
            $order = 'desc';
        }

        $limit = $is_excel ? '' : $page['limit'];

        $customer_record = $model_customer_record->find(array(
            'conditions' => '1=1 '.$conditions,
            'fields' => '*',
            'count' => true,
            'limit' => $limit,
            'order' => "{$sort} {$order}",
        ));

        if($customer_record)
        {
            $page['item_count'] = $model_customer_record->getCount();
            $this->_format_page($page);
            $i = 1;
            foreach($customer_record as $key => $val)
            {
                $customer_record[$key]['no'] = $i+($page['curr_page']-1)*10;
                $customer_record[$key]['return_way'] = $cfg_customer['return_way'][$val['return_way']];
                $customer_record[$key]['reason'] = $cfg_customer['reason'][$val['reason']];
                $customer_record[$key]['return_time'] = !empty($val['return_time']) ? date('Y-m-d',$val['return_time']) : '';
                $i ++;
            }
        }

        $arr['page'] = $page;
        $arr['data'] = $customer_record;

        return $arr ;
    }



    function _get_excel_heads()
    {
        return array(
            'customer_id' => array('name' => "ID" ),
            'customer_name' => array('name' => "客户姓名" ),
            'user_name' => array('name' => "会员名称" ),
            'company' => array('name' => "公司名称"),
            'phone_mob' => array('name' => "手机"),
            'im_qq' => array('name' => "QQ"),
            'email' => array('name' => "E-MALL"),
            'city' => array('name' => "城市"),
            'address' => array('name' => "地址"),
            'customer_ugrade' => array('name' => "客户等级"),
            'source' => array('name' => "资料来源"),
            'reason' => array('name' => "回访原因"),
            'return_way' => array('name' => "回访方式"),
            'return_time' => array('name' => "最后回访时间"),
            're_operator' => array('name' => "操作人"),
        );
    }

    function _get_excel_heads_1()
    {
        return array(
            'no' => array('name' => "编号"),
            'return_time' => array('name' => "回访时间"),
            'return_way' => array('name' => "回访方式"),
            'reason' => array('name' => "回访原因"),
            'return_content' => array('name' => "回访内容"),
            'return_reply' => array('name' => "对方回复"),
            'customer_ugrade' => array('name' => "客户等级"),
            'operator' => array('name' => "操作人"),
        );
    }

    function _get_excel_heads_2()
    {
        return array(
            'no' => array('name' => "编号"),
            'return_time' => array('name' => "咨询时间"),
            'return_way' => array('name' => "咨询方式"),
            'reason' => array('name' => "咨询原因"),
            'return_content' => array('name' => "咨询内容"),
            'return_reply' => array('name' => "我方回复"),
            'customer_ugrade' => array('name' => "客户等级"),
            'operator' => array('name' => "操作人"),
        );
    }

    function _get_excel_heads_3()
    {
        return array(
            'customer_name' => array('name' => "客户姓名" ),
            'user_name' => array('name' => "会员名称" ),
            'phone_mob' => array('name' => "手机"),
            'im_qq' => array('name' => "QQ"),
            'customer_ugrade' => array('name' => "客户等级"),
            'return_time' => array('name' => "回访时间"),
            'return_way' => array('name' => "回访方式"),
            'reason' => array('name' => "回访原因"),
            'return_content' => array('name' => "回访内容"),
            'return_reply' => array('name' => "对方回复"),
            'operator' => array('name' => "操作人"),
        );
    }

    /**
     * 客户管理配置信息
     */
    function _get_cfg_msg()
    {
        $cfg_customer = array(
            'customer_ugrade' =>array(
                '1' => 'A.VIP客户',
                '2' => 'B.已成交客户',
                '3' => 'C.有意向客户',
                '4' => 'D.目标客户',
                '5' => 'E.无意向',
                '6' => 'F.万菱员工',
            ),
            'source' =>array(
                '1' => '网站会员',
                '2' => 'WI-FI后台',
                '3' => '名片收集',
                '4' => '微信',
                '5' => '在线咨询 ',
            ),
            'return_way' =>array(
                '1' => '电话',
                '2' => '短信',
                '3' => 'QQ',
                '4' => '邮件',
                '5' => '邮寄',
            ),
            'reason' =>array(
                '1' => '咨询',
                '2' => '投诉',
                '3' => '新注册会员回访',
                '4' => '未付款订单营销',
                '5' => '满意度回访',
                '6' => '短信优惠营销',
                '7' => '微信优惠营销',
                '8' => '邮件优惠营销',
                '9' => '电话营销',
            ),
        );

        return $cfg_customer;
    }

    private  function export_excel($filename,$key,$trs){
        $filename = iconv("utf-8", "gb2312", $filename);
        header("Content-Type: application/vnd.ms-execl");
        header("Content-Disposition: attachment; filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");

        $tline="\r\n";
        $nx="	";
        if($key){
            foreach($key as $v){
                echo iconv("utf-8", "gb2312", $v['name']).$nx;
            }
        }
        if($trs){
            foreach($trs as $i){
                echo $tline;
                foreach(array_keys($key) as $ik){
                    if($ik=="trans_outtime"){
                        echo iconv("utf-8", "gb2312", date("Y-m-d H:i:s",$i[$ik])).$nx;
                    }else{
                        echo iconv("utf-8", "gb2312", $i[$ik]).$nx;
                    }
                }
            }
        }
    }
}
?>
